import React, { useState, useEffect, useCallback } from 'react';
import { Card, Button, Typography, Spin, Empty } from 'antd';
import { HeartOutlined } from '@ant-design/icons';
import { clientApi } from '../../services/api';
import { useNavigate } from 'react-router-dom';
import { getUser } from '../../utils/auth';

const { Title, Text, Paragraph } = Typography;

const RecommendPage = () => {
  const navigate = useNavigate();
  const [dishes, setDishes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState(getUser());
  const [loginVisible, setLoginVisible] = useState(false);
  const [favoriteIds, setFavoriteIds] = useState([]);
  const [selectedDish, setSelectedDish] = useState(null);
  const [dishModalVisible, setDishModalVisible] = useState(false);

  const loadCategories = async () => {
    try {
      const response = await clientApi.getCategories();
      setCategories(response.data || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  const loadTags = async () => {
    try {
      const response = await clientApi.getTags();
      setTags(response.data || []);
    } catch (error) {
      console.error('加载标签失败:', error);
    }
  };

  const loadRecommendDishes = async () => {
    setLoading(true);
    try {
      // 获取收藏数最高的50个菜品，然后随机选择10个
      const response = await clientApi.getRecommendedDishes({ limit: 50 });
      const topDishes = response.data || [];
      // 随机排序并取前10个
      const randomDishes = [...topDishes].sort(() => 0.5 - Math.random()).slice(0, 10);
      setDishes(randomDishes);
    } catch (error) {
      console.error('加载推荐菜品失败:', error);
      message.error('加载推荐菜品失败');
    } finally {
      setLoading(false);
    }
  };

  // 查看更多按钮处理函数
  const handleViewMore = () => {
    navigate('/dish-list');
  };

  const loadFavoriteIds = useCallback(async () => {
    if (!user) return;
    try {
      const response = await clientApi.getFavoriteIds(user.id);
      setFavoriteIds(response.data || []);
    } catch (error) {
      console.error('加载收藏列表失败:', error);
    }
  }, [user]);

  useEffect(() => {
    loadCategories();
    loadTags();
    loadRecommendDishes();
    if (user) {
      loadFavoriteIds();
    }
  }, [user, loadFavoriteIds]);

  const handleLogin = (userInfo) => {
    setUser(userInfo);
    saveUser(userInfo);
    setLoginVisible(false);
    message.success(`欢迎回来，${userInfo.nickname}！`);
  };

  const handleLogout = () => {
    setUser(null);
    removeUser();
    setFavoriteIds([]);
    message.success('已退出登录');
  };

  const toggleFavorite = async (dish) => {
    if (!user) {
      setLoginVisible(true);
      return;
    }

    try {
      const isFav = favoriteIds.includes(dish.id);
      if (isFav) {
        await clientApi.removeFavorite(user.id, dish.id);
        setFavoriteIds(prev => prev.filter(id => id !== dish.id));
        message.success('已取消收藏');
      } else {
        await clientApi.addFavorite(user.id, dish.id);
        setFavoriteIds(prev => [...prev, dish.id]);
        message.success('已添加收藏');
      }
    } catch (error) {
      message.error(error.message || '操作失败');
    }
  };

  const showDishDetail = (dish) => {
    setSelectedDish(dish);
    setDishModalVisible(true);
  };

  const getCategoryName = (categoryId) => {
    const category = categories.find(c => c.id === categoryId);
    return category ? category.name : '';
  };

  const getTagName = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.name : '';
  };

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
      onClick: () => navigate('/profile')
    },
    {
      key: 'admin',
      icon: <SettingOutlined />,
      label: '管理后台',
      onClick: () => navigate('/admin')
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout
    }
  ];

  const guestMenuItems = [
    {
      key: 'login',
      icon: <LoginOutlined />,
      label: '登录',
      onClick: () => setLoginVisible(true)
    },
    {
      key: 'admin',
      icon: <SettingOutlined />,
      label: '管理后台',
      onClick: () => navigate('/admin')
    }
  ];

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        background: 'var(--secondary-bg)'
      }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ background: 'var(--secondary-bg)', minHeight: '100vh' }}>
      {/* 顶部用户信息区域 */}
      <div style={{
        background: 'var(--primary-bg)',
        padding: '60px 20px 20px',
        borderBottom: '1px solid var(--border-light)',
        position: 'relative'
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: '16px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Avatar
              size={40}
              icon={<UserOutlined />}
              style={{ background: 'var(--accent-primary)' }}
            />
            <div>
              {user ? (
                <>
                  <Text style={{ fontSize: '16px', fontWeight: 600, color: 'var(--text-primary)' }}>
                    {user.nickname}
                  </Text>
                  <Text style={{ fontSize: '12px', color: 'var(--text-secondary)', display: 'block' }}>
                    欢迎回来
                  </Text>
                </>
              ) : (
                <>
                  <Text style={{ fontSize: '16px', fontWeight: 600, color: 'var(--text-primary)' }}>
                    游客
                  </Text>
                  <Text style={{ fontSize: '12px', color: 'var(--text-secondary)', display: 'block' }}>
                    请先登录
                  </Text>
                </>
              )}
            </div>
          </div>

          <Dropdown
            menu={{ items: user ? userMenuItems : guestMenuItems }}
            placement="bottomRight"
            trigger={['click']}
          >
            <Button
              type="text"
              icon={<MoreOutlined />}
              style={{
                color: 'var(--text-tertiary)',
                fontSize: '18px',
                padding: '8px',
                borderRadius: '50%'
              }}
            />
          </Dropdown>
        </div>

        <Title level={2} style={{
          margin: 0,
          fontSize: '24px',
          fontWeight: 700,
          color: 'var(--text-primary)',
          lineHeight: 1.2
        }}>
          今日推荐
        </Title>
        <Text style={{
          color: 'var(--text-secondary)',
          fontSize: '14px',
          marginTop: '4px',
          display: 'block'
        }}>
          为您精选的美味佳肴
        </Text>
      </div>

      <div style={{ padding: '20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Title level={2} style={{ margin: 0, fontSize: '20px', fontWeight: 600, color: 'var(--text-primary)' }}>
          推荐菜品
        </Title>
        <Button type="primary" onClick={handleViewMore}>查看更多</Button>
      </div>
        {dishes.length === 0 ? (
          <div style={{
            textAlign: 'center',
            padding: '60px 20px'
          }}>
            <Empty
              description={
                <div>
                  <Text style={{ color: 'var(--text-secondary)', fontSize: '16px' }}>
                    暂无推荐菜品
                  </Text>
                  <br />
                  <Text style={{ color: 'var(--text-tertiary)', fontSize: '14px' }}>
                    请稍后再试或联系管理员
                  </Text>
                </div>
              }
            />
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {dishes.map(dish => (
              <Card
                key={dish.id}
                hoverable
                className="modern-dish-card"
                onClick={() => showDishDetail(dish)}
                style={{
                  borderRadius: '16px',
                  overflow: 'hidden',
                  boxShadow: 'var(--shadow-light)'
                }}
                cover={
                  <Image
                    alt={dish.name}
                    src={dish.imageUrl}
                    preview={false}
                    style={{
                      width: '100%',
                      height: '200px',
                      objectFit: 'cover'
                    }}
                  />
                }
                actions={[
                  <Button
                    key="favorite"
                    type="text"
                    icon={
                      favoriteIds.includes(dish.id) ? 
                        <HeartFilled style={{ color: '#ff4757' }} /> : 
                        <HeartOutlined />
                    }
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleFavorite(dish);
                    }}
                    style={{ fontSize: '16px' }}
                  >
                    {favoriteIds.includes(dish.id) ? '已收藏' : '收藏'}
                  </Button>,
                  <Button
                    key="detail"
                    type="text"
                    icon={<PlusOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      showDishDetail(dish);
                    }}
                    style={{ fontSize: '16px' }}
                  >
                    详情
                  </Button>
                ]}
              >
                <Card.Meta
                  title={
                    <Text style={{
                      fontSize: '18px',
                      fontWeight: 600,
                      color: 'var(--text-primary)',
                      marginBottom: '4px',
                      display: 'block'
                    }}>
                      {dish.name}
                    </Text>
                  }
                  description={
                    <>
                      <Text style={{
                        color: 'var(--text-secondary)',
                        fontSize: '14px',
                        marginBottom: '12px',
                        display: 'block',
                        lineHeight: 1.4
                      }}>
                        {dish.description}
                      </Text>
                      <Space wrap>
                        <Tag style={{
                          margin: 0,
                          background: 'var(--tertiary-bg)',
                          border: '1px solid var(--border-light)',
                          color: 'var(--text-secondary)',
                          borderRadius: '12px',
                          padding: '2px 8px',
                          fontSize: '12px'
                        }}>
                          {getCategoryName(dish.categoryId)}
                        </Tag>
                        {dish.tags && dish.tags.map(tagId => (
                          <Tag key={tagId} style={{
                            margin: 0,
                            background: 'rgba(26, 115, 232, 0.1)',
                            border: '1px solid rgba(26, 115, 232, 0.2)',
                            color: 'var(--accent-primary)',
                            borderRadius: '12px',
                            padding: '2px 8px',
                            fontSize: '12px'
                          }}>
                            {getTagName(tagId)}
                          </Tag>
                        ))}
                      </Space>
                    </>
                  }
                />
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* 菜品详情模态框 */}
      <Modal
        open={dishModalVisible}
        onCancel={() => setDishModalVisible(false)}
        footer={null}
        centered
        style={{ top: 0 }}
        bodyStyle={{ padding: 0 }}
        width="90%"
        maxWidth="400px"
      >
        {selectedDish && (
          <div style={{ background: 'var(--primary-bg)' }}>
            <Image
              alt={selectedDish.name}
              src={selectedDish.imageUrl}
              preview={false}
              style={{
                width: '100%',
                height: '250px',
                objectFit: 'cover',
                borderRadius: '16px 16px 0 0'
              }}
            />
            <div style={{ padding: '20px' }}>
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'flex-start',
                marginBottom: '16px'
              }}>
                <div style={{ flex: 1 }}>
                  <Title level={3} style={{
                    margin: 0,
                    fontSize: '20px',
                    fontWeight: 600,
                    color: 'var(--text-primary)',
                    lineHeight: 1.3
                  }}>
                    {selectedDish.name}
                  </Title>
                  <Text style={{
                    color: 'var(--text-secondary)',
                    fontSize: '14px',
                    marginTop: '4px',
                    display: 'block'
                  }}>
                    {getCategoryName(selectedDish.categoryId)}
                  </Text>
                </div>
                <Button
                  type="text"
                  icon={
                    favoriteIds.includes(selectedDish.id) ? 
                      <HeartFilled style={{ color: '#ff4757' }} /> : 
                      <HeartOutlined />
                  }
                  onClick={() => toggleFavorite(selectedDish)}
                  style={{ fontSize: '20px', padding: '4px' }}
                />
              </div>

              <Paragraph style={{
                color: 'var(--text-secondary)',
                fontSize: '15px',
                lineHeight: 1.6,
                marginBottom: '16px'
              }}>
                {selectedDish.description}
              </Paragraph>

              <div style={{ marginBottom: '20px' }}>
                <Text style={{
                  fontSize: '14px',
                  fontWeight: 600,
                  color: 'var(--text-primary)',
                  marginBottom: '8px',
                  display: 'block'
                }}>
                  标签
                </Text>
                <Space wrap>
                  {selectedDish.tags && selectedDish.tags.map(tagId => (
                    <Tag key={tagId} style={{
                      background: 'rgba(26, 115, 232, 0.1)',
                      border: '1px solid rgba(26, 115, 232, 0.2)',
                      color: 'var(--accent-primary)',
                      borderRadius: '12px',
                      padding: '4px 12px',
                      fontSize: '13px'
                    }}>
                      {getTagName(tagId)}
                    </Tag>
                  ))}
                </Space>
              </div>
            </div>
          </div>
        )}
      </Modal>

      <LoginModal
        visible={loginVisible}
        onCancel={() => setLoginVisible(false)}
        onSuccess={handleLogin}
      />
    </div>
  );
};

export default RecommendPage;